# -*- coding: UTF-8 _*_

import os
import time
import allure

from loguru import logger

from common.readconfig import ReadConfig
from config.config import base_path

app_jpg_path = base_path + ReadConfig.parse_yaml(filename='config/appconfig.yaml', key='path.jpg')
if not os.path.exists(app_jpg_path):
    os.mkdir(app_jpg_path)


class APPBase():
    def __init__(self, driver):
        self.driver = driver
        self.timeout = 30

    # 判断元素是否存在
    def isElementLocated(self, locator='', pagename='', elename='', doc='判断元素是否存在'):
        if not isinstance(locator, tuple):
            logger.error(f"页面--{pagename}:{doc}'{elename}'，locator类型错误，必须传入元组类型，locator=（‘定位方法’，‘值’）")
            return False
        else:
            with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
                try:
                    if locator[0].lower() == 'resourceId'.lower():
                        result = self.driver(resourceId=locator[1]).wait(self.timeout)
                    elif locator[0].lower() == 'text'.lower():
                        result = self.driver(text=locator[1]).wait(self.timeout)
                    elif locator[0].lower() == 'className'.lower():
                        result = self.driver(className=locator[1]).wait(self.timeout)
                    elif locator[0].lower() == 'description'.lower():
                        result = self.driver(description=locator[1]).wait(self.timeout)
                    elif locator[0].lower() == 'xpath'.lower():
                        result = self.driver.xpath(locator[1]).wait(self.timeout)
                    else:
                        logger.error(f"页面--{pagename}:{doc}'{elename}'，定位方法{locator[0]}错误，只能传入resourceId，text，"
                                     f"className，description，xpath")
                        return False
                    if not result:
                        logger.debug(f"页面--{pagename}:'{elename}'不存在,定位方法'{locator[0]}',value值'{locator[1]}'")
                    else:
                        logger.debug(f"页面--{pagename}:'{elename}'存在,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return result
                except:
                    logger.error(f"页面--{pagename}:{doc}'{elename}'失败,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return False

    # 查找元素
    def findElement(self, locator='', pagename='', elename='', doc='查找元素'):
        if not isinstance(locator, tuple):
            logger.error(f"页面--{pagename}:{doc}'{elename}'，locator类型错误，必须传入元组类型，locator=（‘定位方法’，‘值’）")
            raise
        else:
            with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
                if self.isElementLocated(locator=locator, pagename=pagename, elename=elename):
                    if locator[0].lower() == 'resourceId'.lower():
                        element = self.driver(resourceId=locator[1])
                    elif locator[0].lower() == 'text'.lower():
                        element = self.driver(text=locator[1])
                    elif locator[0].lower() == 'className'.lower():
                        element = self.driver(className=locator[1])
                    elif locator[0].lower() == 'description'.lower():
                        element = self.driver(description=locator[1])
                    elif locator[0].lower() == 'xpath'.lower():
                        element = self.driver.xpath(locator[1])
                    logger.debug(f"页面--{pagename}:{doc}'{elename}'成功,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return element
                else:
                    logger.debug(f"页面--{pagename}:'{elename}'不存在,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return None

    # 查找元素组
    def findElements(self, locator='', pagename='', elename='', doc='查找元素组'):
        if not isinstance(locator, tuple):
            logger.error(f"页面--{pagename}:{doc}'{elename}'，locator类型错误，必须传入元组类型，locator=（‘定位方法’，‘值’）")
            raise
        else:
            with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
                if self.isElementLocated(locator=locator, pagename=pagename, elename=elename):
                    elements = []
                    if locator[0].lower() == 'resourceId'.lower():
                        element = self.driver(resourceId=locator[1])
                    elif locator[0].lower() == 'text'.lower():
                        element = self.driver(text=locator[1])
                    elif locator[0].lower() == 'className'.lower():
                        element = self.driver(className=locator[1])
                    elif locator[0].lower() == 'description'.lower():
                        element = self.driver(description=locator[1])
                    elif locator[0].lower() == 'xpath'.lower():
                        element = self.driver.xpath(locator[1])
                    for i in range(0, len(element)):
                        elements.append(element[i])
                    logger.debug(f"页面--{pagename}:{doc}'{elename}'成功,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return elements
                else:
                    logger.debug(f"页面--{pagename}:'{elename}'不存在,定位方法'{locator[0]}',value值'{locator[1]}'")
                    return None

    # 通过定位的元素，点击
    def clickbyele(self, ele='', pagename='', elename='', doc='点击元素组'):
        if not isinstance(ele, object):
            logger.error(f"页面--{pagename}:{doc}'{elename}'，ele类型错误，必须传入 元素对象")
            raise
        with allure.step(f"页面--{pagename}:{doc}'{elename}'"):
            ele.click()
            logger.debug(f"页面--{pagename}:{doc}'{elename}'成功")

    # 点击单个元素
    def click(self, locator='', pagename='', elename='', doc='点击元素'):
        element = self.findElement(locator=locator, pagename=pagename, elename=elename)
        with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
            element.click()
            logger.debug(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'")

    # 获取单个元素文本
    def gettext(self, locator='', pagename='', elename='', doc='获取单个元素文本'):
        element = self.findElement(locator=locator, pagename=pagename, elename=elename)
        with allure.step(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'"):
            logger.debug(f"页面--{pagename}:{doc}'{elename}',定位方法'{locator[0]}',value值'{locator[1]}'")
            return element.get_text()

    # 通过元素获取文本
    def gettextbyele(self, ele='', pagename='', elename='', doc='获取一组元素文本'):
        if not isinstance(ele, object):
            logger.error(f"页面--{pagename}:{doc}'{elename}'，ele类型错误，必须传入 元素对象")
            raise
        with allure.step(f"页面--{pagename}:{doc}'{elename}'"):
            res = ele.get_text()
            # print(res)
            logger.debug(f"页面--{pagename}:{doc}'{elename}'成功")
            return res

    # 获取一组元素文本
    def gettextsbyele(self, ele='', pagename='', elename='', doc='获取一组元素文本'):
        if not isinstance(ele, list):
            logger.error(f"页面--{pagename}:{doc}'{elename}'，ele类型错误，必须传入列表")
            raise
        with allure.step(f"页面--{pagename}:{doc}'{elename}'"):
            texts = []
            for i in ele:
                if not isinstance(i, object):
                    logger.error(f"页面--{pagename}:{doc}'{elename}'，ele中数据错误，必须传入 元素对象")
                else:
                    texts.append(i.get_text())
            logger.debug(f"页面--{pagename}:{doc}'{elename}'成功")
            return texts

    @classmethod
    def save_myscreenshot(cls, driver, pagename=""):
        image_name = app_jpg_path + f"{pagename}_{time.strftime('%Y-%m-%d_%H_%M_%S', time.localtime())}.jpg"
        driver.screenshot(image_name)
        with open(image_name, mode='rb') as f:
            file = f.read()
        allure.attach(file, image_name, allure.attachment_type.JPG)
        logger.debug(f"页面:'{pagename}'截图成功, 文件名:{image_name}")

    # 获取一组元素文本
    @classmethod
    def clickback(cls, driver):
        # print(driver)
        driver.press('back')
        logger.debug(f"使用物理 返回 键")

    # 滑动屏幕
    @classmethod
    def swipescreen(cls, driver):
        # print(driver)
        x, y = driver.window_size()
        driver.swipe(x * 0.5, 1796, x * 0.5, 352, duration=0.5)
        time.sleep(10)
        # driver(scrollable=True).scroll.toEnd()
        logger.debug(f"向上滑动 屏幕")
